package com.lanou3g.bookstore.book.web.servlet;

import com.lanou3g.bookstore.book.domain.Book;
import com.lanou3g.bookstore.book.service.BookService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "BookServlet", urlPatterns = "/book.do")
public class BookServlet extends HttpServlet {
    private BookService service = new BookService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Book> books = null;
        String cid1 = request.getParameter("cid");
        String bid1 = request.getParameter("bid");
        if (cid1 == null) {
            if (bid1 == null){
                books = service.findAll();
                request.setAttribute("books", books);
                request.getRequestDispatcher("/jsps/book/list.jsp")
                        .forward(request, response);
            } else {
                Book book = service.load(bid1);
                request.setAttribute("book", book);
                request.getRequestDispatcher("/jsps/book/desc.jsp")
                        .forward(request, response);
            }
        } else {
            Integer cid = Integer.valueOf(cid1);
            books = service.findByCategory(cid);
            request.setAttribute("books", books);
            request.getRequestDispatcher("/jsps/book/list.jsp")
                    .forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
